from django.db import models
from rest_framework import serializers

import tree.models


# Create your models here.
class Address(models.Model):
    id = models.AutoField(primary_key=True)
    province = models.CharField(max_length=100, blank=True, null=True)  # 省份
    city = models.CharField(max_length=100, blank=True, null=True)  # 市
    county = models.CharField(max_length=100, blank=True, null=True)  # 县、区
    town = models.CharField(max_length=100, blank=True, null=True)  # 乡、镇
    name = models.CharField(max_length=100, unique=True, blank=True, null=True)  # 样地名称
    detail = models.CharField(max_length=255, blank=True, null=True)  # 详细信息

    class Meta:
        db_table = 'field_address'
        ordering = ['city', 'county', 'name']


class AddressSerializer(serializers.ModelSerializer):
    tree_count = serializers.SerializerMethodField()  # 关联样木量

    class Meta:
        model = Address
        fields = '__all__'

    def get_tree_count(self, obj):
        """样木量"""
        trees = tree.models.Tree.objects.all().filter(address=obj)
        return len(trees)


# 树种
class TreeSpecies(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30, unique=True, null=False, verbose_name='树种名称')
    status = models.IntegerField(null=True, verbose_name="状态（1正常 0停用）")
    create_time = models.DateField(null=True, verbose_name="创建时间", )
    update_time = models.DateField(null=True, verbose_name="更新时间")
    remark = models.CharField(max_length=500, null=True, verbose_name="备注")

    class Meta:
        db_table = 'field_treeSpecies'


class TreeSpeciesSerializer(serializers.ModelSerializer):
    tree_count = serializers.SerializerMethodField()  # 关联样木量

    class Meta:
        model = TreeSpecies
        fields = '__all__'

    def get_tree_count(self, obj):
        """计算样木量"""
        trees = tree.models.Tree.objects.all().filter(treeSpecies=obj)
        return len(trees)
